import os,sys

from pathlib import Path
import json
import time

sys.path.append(str(Path(__file__).resolve().parent))

from wechat_ocr.ocr_manager import OcrManager, OCR_MAX_TASK_ID
from hp.TcpPullSeverClient import MySocketEvent,Server
# from hp import MySocketEvent,Server

from PIL import Image
import io
import base64
import random

# wechat_ocr_dir = r"D:\mycode\王者传奇\wechatocr\extracted\WeChatOCR.exe"  # OCR的地址，可以用everythin工具查找一下地址
wechat_ocr_dir = r".\ocr\WeChatOCR.exe"  # OCR的地址，可以用everythin工具查找一下地址
wechat_dir = r".\ocr"  # 一定是要包含mmmojo.dll的路径

queue_list = []

def img2png(img: bytes = None, img_path: str = None, fiename: str = None):
    if fiename is None:
        out_filename = f"{int(time.time() * 1000)}{random.randint(1000, 9999)}.png"
    else:
        out_filename = fiename
    if img:
        # 假设bmp_bytes包含BMP图像的字节数据
        # 将BMP字节流转换为PIL图像
        image = Image.open(io.BytesIO(img))
        # 将PIL图像转换为PNG格式的字节流
        image.convert("RGBA").save(out_filename, format="PNG")
    else:
        # 打开图片文件
        with Image.open(img_path) as img:
            # 转换为PNG格式
            img.convert('RGB').save(out_filename, format='PNG')
    return out_filename


def get_img_client_data(img: str):
    global queue_list
    for index, item in enumerate(queue_list):
        print("查找数据",item["img"].lower(),img.lower())
        image_path=item["img"].replace("/","\\")
        print("查找数据", image_path, img.lower())
        if image_path.lower() in img.lower():
            client_data = queue_list.pop(index)
            return client_data
    return None

def ocr_result_callback(img_path: str, results: dict):
    """
    OCR 结果回调函数
    """
    print(f"识别成功，img_path: {img_path}")
    print("OCR 结果：", results)
    response = json.dumps(results, ensure_ascii=False, indent=2)
    client_data = get_img_client_data(img=img_path)
    print("client_data", client_data)
    if client_data:
        svr.Answer(ConnID=client_data["ConnID"], apiCode=client_data["ApiCode"], flag=client_data["flag"],
                   data=response.encode())
        if client_data["tempfile"]:
            os.remove(img_path)
    else:
        print("查找客户端ID失败....")


class MyServerEvent(MySocketEvent):
    def __init__(self):
        super().__init__()

    def OnRequest(self, data, flag, ApiCode, ConnID):
        '''
        请求到达
        :param data: 数据
        :param flag: 标识
        :param ApiCode: APICODE
        :param ConnID: 连接ID 若是客户端 此参数为None
        :return:
        '''
        print("请求到达",data)
        print(f"客户请求{ConnID}:{ApiCode},数据：{data}")
        try:

            data = json.loads(data)
            img = data["img"]
            t = time.time()
            if os.path.exists(img):
                out_filename = img
                tempfile = False
            else:
                img = base64.b64decode(img)
                out_filename = img2png(img=img)
                tempfile = True
            print("转换用时", time.time() - t)
            global queue_list
            queue_list.append(
                {"ConnID": ConnID, "ApiCode": ApiCode, "flag": flag, "img": out_filename, "tempfile": tempfile})
            ocr_manager.DoOCRTask(out_filename)
        except Exception as E:
            print("数据解析异常！")


if __name__ == "__main__":
    import sys
    if len(sys.argv) == 2:
        port = int(sys.argv[1])
    else:
        port = 48891
    # 创建 OCR 管理器实例
    ocr_manager = OcrManager(wechat_dir)
    # 设置 WeChatOCR 目录
    ocr_manager.SetExePath(wechat_ocr_dir)
    # 设置微信所在路径
    ocr_manager.SetUsrLibDir(wechat_dir)
    # 设置 OCR 识别结果的回调函数
    ocr_manager.SetOcrResultCallback(ocr_result_callback)
    # 启动 OCR 服务
    ocr_manager.StartWeChatOCR()
    print("port", port)
    svr = Server('127.0.0.1', port, mySocketEvent=MyServerEvent())
    svr.Start()
    # cnt = Client('127.0.0.1', port)
    # cnt.Start()
    while True:
        time.sleep(5)
        # msg = {"img": "D:\\mycode\\王者传奇\\5.PNG"}
        # msg = json.dumps(msg)
        # t = time.time()
        # resdata = cnt.Sync_SendData(apiCode=1001, data=msg.encode(), outTime=15)
        # if resdata:
        #     resdata = resdata.decode()
        #     resdata = json.loads(resdata)
        #     print("请求返回", resdata)
        #     print("识别用时", time.time() - t)
        # else:
        #     print("请求识别失败！")
        # break
    # 消毁服务
    ocr_manager.KillWeChatOCR()
